package com.yjy.quartz.web;


import com.alibaba.fastjson.JSON;
import com.yjy.quartz.entity.QuartzEntity;
import com.yjy.quartz.entity.Result;
import com.yjy.quartz.service.IJobService;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/job")
public class JobController {

    private final static Logger LOGGER = LoggerFactory.getLogger(JobController.class);

    @Autowired
    private Scheduler scheduler;
    @Autowired
    private IJobService jobService;

    @PostMapping("/list")
    public Result list(QuartzEntity quartz, Integer pageNo, Integer pageSize) throws SchedulerException {
        LOGGER.info("任务列表：quartz={}, pageNo={}, pageSize={}", JSON.toJSONString(quartz), pageNo, pageSize);
        return jobService.listQuartzEntity(quartz, pageNo, pageSize);
    }

    @PostMapping("/add")
    public Result save(@RequestBody QuartzEntity quartz) {
        LOGGER.info("保存任务（新增/保存）：quartz={}", JSON.toJSONString(quartz));
        try {
            jobService.save(quartz);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        }
        return Result.ok();
    }

    @PostMapping("/trigger")
    public Result trigger(@RequestBody QuartzEntity quartz, HttpServletResponse response) {
        LOGGER.info("触发任务 quartz={}", JSON.toJSONString(quartz));
        try {
            JobKey key = new JobKey(quartz.getJobName(), quartz.getJobGroup());
            scheduler.triggerJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return Result.error();
        }
        return Result.ok();
    }

    @PostMapping("/pause")
    public Result pause(@RequestBody QuartzEntity quartz, HttpServletResponse response) {
        LOGGER.info("暂停任务 quartz={}", JSON.toJSONString(quartz));
        try {
            JobKey key = new JobKey(quartz.getJobName(), quartz.getJobGroup());
            scheduler.pauseJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return Result.error();
        }
        return Result.ok();
    }

    @PostMapping("/resume")
    public Result resume(@RequestBody QuartzEntity quartz, HttpServletResponse response) {
        LOGGER.info("恢复任务 quartz={}", JSON.toJSONString(quartz));
        try {
            JobKey key = new JobKey(quartz.getJobName(), quartz.getJobGroup());
            scheduler.resumeJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return Result.error();
        }
        return Result.ok();
    }

    @PostMapping("/remove")
    public Result remove(@RequestBody QuartzEntity quartz, HttpServletResponse response) {
        LOGGER.info("移除任务 quartz={}", JSON.toJSONString(quartz));
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(quartz.getJobName(), quartz.getJobGroup());
            // 停止触发器  
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器  
            scheduler.unscheduleJob(triggerKey);
            // 删除任务  
            scheduler.deleteJob(JobKey.jobKey(quartz.getJobName(), quartz.getJobGroup()));
            System.out.println("removeJob:" + JobKey.jobKey(quartz.getJobName()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        }
        return Result.ok();
    }
}
